package cn.xd.core.utils;

import cn.xd.core.ddd.entity.Entity;
import cn.xd.core.ddd.value.IdValue;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * @author: mirzaLin
 * @data: 2023/11/19
 * @description: 快照工具类
 **/
@Slf4j
public class SnapshotUtils {
    public static <T extends Entity<? extends IdValue>> T snapshot(T t) {
        T retobj = null;
        try {
            //写入流中
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(t);
            //从流中读取
            ObjectInputStream ios = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
            retobj = (T) ios.readObject();
        } catch (Exception e) {
            log.error("快照失败" + e);
        }
        return retobj;
    }
}
